package com.ruoyi.web.controller.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 水量统计分析任务
 * @data 2025/10/10 17:28
 */
@Component
public class WaterAnalysisTask {

    Logger log = LoggerFactory.getLogger(WaterAnalysisTask.class);

    @Autowired
    private IWaterMeterService waterMeterService;
    @Autowired
    private IWaterYcmeterDatahistoryService historyService;
    @Autowired
    private IWaterDailyUsageService waterDailyUsageService;
    @Autowired
    private IWaterWeeklyUsageService waterWeeklyUsageService;
    @Autowired
    private IWaterMonthlyUsageService waterMonthlyUsageService;

    /**
     * 每日凌晨 2点执行一次 日用水量统计
     */
    @Scheduled(cron = "0 30 2 * * ?")
    public void analysisDayUsage() {
        System.out.println("开始执行水表数据统计任务");
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0"); // 0:远传表
        List<WaterMeter> waterMeters =waterMeterService.selectWaterMeterList(waterMeter);
        WaterYcmeterDatahistory dataHistory = new WaterYcmeterDatahistory();
        String previousDay = DateUtils.getPreviousDay(DateUtils.getDate());
        String startTime = previousDay +" 00:00";  // 获取前一天的开始时间
        dataHistory.setStartTime(startTime);
        List<WaterYcmeterDatahistory> dataHistoryList = historyService.selectWaterYcmeterDatahistoryList(dataHistory);
        Map<String, List<WaterYcmeterDatahistory>> dataHistoryMap = dataHistoryList.stream()
                .collect(Collectors.groupingBy(WaterYcmeterDatahistory::getMeterNo));
        for(WaterMeter meter : waterMeters){
            List<WaterYcmeterDatahistory> dataList = dataHistoryMap.get(meter.getMeterNo());
            if (StringUtils.isEmpty(dataList)) {
                continue;
            }
            dataList.sort(Comparator.comparing(WaterYcmeterDatahistory::getReadDate,
                    Comparator.nullsLast(String::compareTo))); // 正序 排序
            WaterYcmeterDatahistory firstData = dataList.get(0);
            WaterYcmeterDatahistory lastData = dataList.get(dataList.size()-1);
            if (!(firstData.getReadDate().endsWith(" 00:00")&&lastData.getReadDate().endsWith(" 00:00"))) {
                continue;
            }
            BigDecimal a = new BigDecimal(firstData.getCurrentReading());
            BigDecimal b = new BigDecimal(lastData.getCurrentReading());
            BigDecimal c = b.subtract(a); // 计算用水量
            WaterDailyUsage dailyUsage = new WaterDailyUsage();
            dailyUsage.setUserId(meter.getUserId());
            dailyUsage.setMeterNo(meter.getMeterNo());
            dailyUsage.setUserName(meter.getUserName());
            dailyUsage.setPreviousReading(a);
            dailyUsage.setCurrentReading(b);
            dailyUsage.setDailyConsumption(c);
            dailyUsage.setReadingDate(previousDay);
            waterDailyUsageService.insertWaterDailyUsage(dailyUsage);
        }
    }

    /**
     * 每周一凌晨 3点执行一次 周用水量统计
     */
    @Scheduled(cron = "0 30 3 ? * MON")
    public void analysisWeekUsage(){
        String startDateStr = DateUtils.getPreviousWeek(); // 获取上周的开始时间
        String endDateStr = DateUtils.getPreviousDay(DateUtils.getDate()); // 获取上周的结束时间
        log.error("开始执行周用水量统计任务,参数："+startDateStr+","+endDateStr);
        Date d1 = DateUtils.parseDate(startDateStr);
        Date d2 = DateUtils.parseDate(endDateStr);
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0"); // 0:远传表
        List<WaterMeter> waterMeters =waterMeterService.selectWaterMeterList(waterMeter);
        WaterDailyUsage waterDailyUsage = new WaterDailyUsage();
        waterDailyUsage.setStartDay(startDateStr);
        waterDailyUsage.setEndDay(endDateStr);
        // 获取上周所有水表的日用水量
        List<WaterDailyUsage> dailyUsageList = waterDailyUsageService.selectWaterDailyUsageList(waterDailyUsage);
        Map<String, List<WaterDailyUsage>> dailyUsageMap = dailyUsageList.stream()
                .collect(Collectors.groupingBy(WaterDailyUsage::getMeterNo));
        for(WaterMeter meter : waterMeters){
            List<WaterDailyUsage> meterDailyUsageList = dailyUsageMap.get(meter.getMeterNo());
            if (StringUtils.isEmpty(meterDailyUsageList)) {
                continue;
            }
            meterDailyUsageList.sort(Comparator.comparing(WaterDailyUsage::getReadingDate,
                    Comparator.nullsLast(String::compareTo)));
            BigDecimal a = meterDailyUsageList.get(0).getPreviousReading();
            BigDecimal b = meterDailyUsageList.get(meterDailyUsageList.size()-1).getCurrentReading();
            BigDecimal c = b.subtract(a); // 计算周用水量
            WaterWeeklyUsage waterWeeklyUsage = new WaterWeeklyUsage();
            waterWeeklyUsage.setUserId(meter.getUserId());
            waterWeeklyUsage.setMeterNo(meter.getMeterNo());
            waterWeeklyUsage.setUserName(meter.getUserName());
            waterWeeklyUsage.setStartDate(d1);
            waterWeeklyUsage.setEndDate(d2);
            waterWeeklyUsage.setWeeklyConsumption(c);
            waterWeeklyUsageService.insertWaterWeeklyUsage(waterWeeklyUsage);
        }
    }

    /**
     * 每月1号凌晨 4点执行一次 月用水量统计
     */
    @Scheduled(cron = "0 30 4 1 * ?")
    public void analysisMonthUsage(){
        String startDateStr = DateUtils.getPreviousMonth(); // 获取上月的开始时间
        String endDateStr = DateUtils.getPreviousDay(DateUtils.getDate()); // 获取上月的结束时间
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0"); // 0:远传表
        List<WaterMeter> waterMeters =waterMeterService.selectWaterMeterList(waterMeter);
        WaterDailyUsage waterDailyUsage = new WaterDailyUsage();
        waterDailyUsage.setStartDay(startDateStr);
        waterDailyUsage.setEndDay(endDateStr);
        // 获取上月所有水表的日用水量
        List<WaterDailyUsage> dailyUsageList = waterDailyUsageService.selectWaterDailyUsageList(waterDailyUsage);
        Map<String, List<WaterDailyUsage>> dailyUsageMap = dailyUsageList.stream()
                .collect(Collectors.groupingBy(WaterDailyUsage::getMeterNo));
        for(WaterMeter meter : waterMeters){
            List<WaterDailyUsage> meterDailyUsageList = dailyUsageMap.get(meter.getMeterNo());
            if (StringUtils.isEmpty(meterDailyUsageList)) {
                continue;
            }
            meterDailyUsageList.sort(Comparator.comparing(WaterDailyUsage::getReadingDate,
                    Comparator.nullsLast(String::compareTo)));
            BigDecimal a = meterDailyUsageList.get(0).getPreviousReading();
            BigDecimal b = meterDailyUsageList.get(meterDailyUsageList.size()-1).getCurrentReading();
            BigDecimal c = b.subtract(a); // 计算月用水量
            WaterMonthlyUsage waterMonthlyUsage = new WaterMonthlyUsage();
            waterMonthlyUsage.setUserId(meter.getUserId());
            waterMonthlyUsage.setMeterNo(meter.getMeterNo());
            waterMonthlyUsage.setUserName(meter.getUserName());
            waterMonthlyUsage.setMonth(startDateStr.substring(0, 7));
            waterMonthlyUsage.setMonthlyConsumption(c.doubleValue());
            waterMonthlyUsageService.insertWaterMonthlyUsage(waterMonthlyUsage);
        }
    }
}
